package com.szbmyoubao.app.base

import androidx.lifecycle.viewModelScope
import com.szbmyoubao.app.base.vm.PageIntent
import com.szbmyoubao.app.base.vm.PageState
import com.szbmyoubao.app.bean.response.BaseListResponse
import com.szbmyoubao.app.http.ApiService
import com.szbmyoubao.app.http.request
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.base.view.IUiIntent
import com.ellecity06.common.base.view.IUiState
import com.ellecity06.common.http.entity.ApiResponse
import com.ellecity06.common.ktx.SharedFlowEvents
import com.ellecity06.common.ktx.postEvent
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/10/24 15:26
 * @des
 */
abstract class BasePageViewModel<T : IUiState, D : IUiIntent> : BaseMviViewModel<T, D>() {

    //创建意图管道，容量无限大
    val pageIntent = Channel<PageIntent>(Channel.UNLIMITED)

    protected val mPageState = SharedFlowEvents<PageState>()
    val pageState = mPageState.asSharedFlow()

    init {
        viewModelScope.launch {
            //收集意图
            pageIntent.consumeAsFlow().collect {
                when (it) {
                    PageIntent.Refresh -> {
                        pagerHelper.pageIndex = 1
                        fetchData()
                    }

                    PageIntent.LoadMore -> {
                        fetchData()
                    }
                }

            }
        }

    }

    abstract fun fetchData()

    protected suspend fun <T> onFetchPageSuccess(it: List<T>?) {
        if (it != null) {
            if (it.isNotEmpty()) {
                val hasMore = it.size >= pagerHelper.pageSize
                if (pagerHelper.pageIndex == 1) {
                    mPageState.postEvent(PageState.RefreshSuccess(it, hasMore))
                } else {
                    mPageState.postEvent(PageState.LoadMoreSuccess(it, hasMore))
                }
                pagerHelper.pageIndex++
            } else {
                if (pagerHelper.pageIndex == 1) {
                    mPageState.postEvent(PageState.RefreshSuccess(emptyList<T>(), false))
                } else {
                    mPageState.postEvent(PageState.NoMore)
                }
            }
        }else {
            if (pagerHelper.pageIndex == 1) {
                mPageState.postEvent(PageState.RefreshSuccess(emptyList<T>(), false))
            } else {
                mPageState.postEvent(PageState.LoadMoreSuccess(emptyList<T>(), false))
            }
        }
    }

    protected fun onFetchPageError(msg: String?) {
        if (pagerHelper.pageIndex == 1) {
            viewModelScope.launch { mPageState.postEvent(PageState.RefreshError(msg?:"未知错误")) }
        } else {
            viewModelScope.launch { mPageState.postEvent(PageState.LoadError) }
        }

    }

    /**
     *
     */
    protected fun <T> requestPageList(api: suspend ApiService.() -> ApiResponse<BaseListResponse<T>>) {
        request(success = {
            it?.ext?.let {
                mPageState.postEvent(PageState.ExtDate(it))
            }

            onFetchPageSuccess(it?.list)
        }, api = api, error = {
            onFetchPageError(it.message)
        })
    }

    protected fun <T> requestList(api: suspend ApiService.() -> ApiResponse<List<T>>) {
        request(success = {
            onFetchPageSuccess(it)
        }, api = api, error = { onFetchPageError(it.message) })
    }
}